﻿namespace Anley.DomainDrivenDesign.Contract.Extension;

/// <summary>
/// 列表扩展类
/// </summary>
public static class ListExtension
{
    /// <summary>
    /// 列表转数据表
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="tableName"></param>
    public static DataTable ListToDataTable<T>(
        this IList<T> list,
        string tableName)
    {
        var properties = typeof(T).GetProperties();
        var dataTable = new DataTable(tableName);
        dataTable.Columns.AddRange(
            properties.Select(column =>
            new DataColumn(column.Name, Nullable.GetUnderlyingType(column.PropertyType) ?? column.PropertyType)).ToArray());
        if (list.Count > 0)
        {
            object? obj;
            object?[] dataRow;
            ArrayList tempList;
            for (int i = 0; i < list.Count; i++)
            {
                tempList = new ArrayList();
                foreach (var pi in properties)
                {
                    obj = pi.GetValue(list.ElementAt(i), null);
                    tempList.Add(obj);
                }
                dataRow = tempList.ToArray();
                dataTable.LoadDataRow(dataRow, true);
            }
        }
        return dataTable;
    }
}